package com.sls.web.manager.action.recharge;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.recharge.pojo.CardImportLog;
import com.sls.web.manager.recharge.pojo.CardInfo;
import com.sls.web.manager.recharge.pojo.Operation;
import com.sls.web.manager.recharge.pojo.PhoneType;
import com.sls.web.manager.recharge.pojo.StockSupplier;
import com.sls.web.manager.recharge.pojo.SystemProduct;
import com.sls.web.manager.recharge.querybean.StockSupplierQuery;
import com.sls.web.manager.recharge.querybean.SystemProductQuery;
import com.sls.web.manager.recharge.service.CardImportLogService;
import com.sls.web.manager.recharge.service.CardInfoService;
import com.sls.web.manager.recharge.service.OperationService;
import com.sls.web.manager.recharge.service.PhoneTypeService;
import com.sls.web.manager.recharge.service.StockSupplierService;
import com.sls.web.manager.recharge.service.SystemProductService;

/**
 * 卡号数据导入功能
 * 
 * @author sxf
 * 
 */
@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"1024000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class CardImportAction extends SuperAction {
	private static final long serialVersionUID = 1L;

	// upload属性用来封装上传的文件
	private File upload;
	// uploadContentType属性用来封装上传文件的类型
	private String uploadContentType;
	// uploadFileName属性用来封装上传文件的文件名
	private String uploadFileName;

	@Resource(name = "cardInfoService")
	private CardInfoService cardInfoService;
	@Resource(name = "cardImportLogService")
	private CardImportLogService cardImportLogService;
	@Resource(name = "systemProductService")
	private SystemProductService systemProductService;
	@Resource(name = "stockSupplierService")
	private StockSupplierService stockSupplierService;
	@Resource(name = "operationService")
	private OperationService operationService;
	@Resource(name = "phoneTypeService")
	private PhoneTypeService phoneTypeService;

	private String errorMsg;// 错误信息
	private String systemProductId;
	private SystemProductQuery systemProductQuery;
	private String cardName;

	private String operatorsType;// 运营商类别
	private String phoneType;// 号码类型

	private String province;// 可充区域
	private String areaCity;// 可充区域

	private String iseffect;// 是否有有效期

	private List<StockSupplier> stockSuppliersList;
	private List<Operation> operationList;// 运营商
	private List<PhoneType> phoneTypeList;// 号码类型
	private String supplier;// 进货源
	private String supplyDate;// 进货日期

	private String useLevel;// 使用级别

	/**
	 * 进到数据导入页面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String cardImport() throws Exception {
		if (StringUtils.isNotBlank(systemProductId)) {
			systemProductQuery = new SystemProductQuery();
			systemProductQuery.setId(systemProductId);
		}
		UserInfoVO userInfoVO = getCurrentOperator();
		SystemProduct sp = systemProductService.queryOne(systemProductQuery,
				userInfoVO);
		if (sp != null) {
			cardName = sp.getName();
		}
		StockSupplierQuery ssq = new StockSupplierQuery();
		stockSuppliersList = stockSupplierService.queryList(ssq,
				getCurrentOperator());

		operationList = operationService.findList(getCurrentOperator());
		if (operationList != null && !operationList.isEmpty()) {
			for (int i = 0; i < operationList.size(); i++) {
				Operation op = operationList.get(i);
				if (op.getEnable() != null && !op.getEnable()) {
					// 过滤无效的运营商
					operationList.remove(i);
				}
			}
		}
		phoneTypeList = phoneTypeService.listEnable(getCurrentOperator());
		if (phoneTypeList != null && !phoneTypeList.isEmpty()) {
			/*for (Iterator<PhoneType> it = phoneTypeList.iterator(); it
					.hasNext();) {
				PhoneType oper = (PhoneType) it.next();
				if ("00".equals(oper.getCode())) {
					it.remove();
				}
			}*/
		}
		return "input";
	}

	/**
	 * 执行数据导入
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	public String doLeadin() throws Exception {

		// 计算时间

		long useTime = System.currentTimeMillis();

		// 设置上传文件目录
		// String uploadPath = ServletActionContext.getServletContext()
		// .getRealPath("/upload");
		// 基于upload创建一个文件输入流
		if (upload == null) {
			errorMsg = "未上传文件!";
			return SUCCESS;
		}
		InputStream is = new FileInputStream(upload);

		// 设置目标文件
		// File toFile = new File(uploadPath, this.getUploadFileName());

		// 创建一个输出流
		// OutputStream os = new FileOutputStream(toFile);

		// 设置缓存
		// byte[] buffer = new byte[1024];

		// int length = 0;

		// 读取upload文件输出到toFile文件中
		// while ((length = is.read(buffer)) > 0) {
		// os.write(buffer, 0, length);
		// }
		log.info("上传文件名:" + uploadFileName);
		log.info("上传文件类型:" + uploadContentType);

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, 2);
		Date twoYearLater = cal.getTime();// 两年后的日期

		Date d = new Date();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");

		Random r = new Random();
		// 入库卡密批次号
		String cardImportBatchNum = sdf1.format(d) + Math.abs(r.nextInt(10000));
		StringBuilder errorMsgSB = new StringBuilder();
		BufferedReader bis = null;
		if (StringUtils.isNotBlank(uploadFileName)
				&& uploadFileName.toLowerCase().endsWith(".txt")) {
			// .txt文件解析
			bis = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String str = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			int strLength = 4;// str长度

			int count = 0;// 计数
			int totalPrice = 0;// 面值(一个批次的面值都是相同的)
			int totalMoney = 0;// 入库卡密金额

			int line = 0;

			int size = 2;
			List<CardInfo> batchList = new ArrayList<CardInfo>(size);
			while ((str = bis.readLine()) != null) {
				line++;
				String[] strArr = str.split("\t");
				if (strArr == null) {
					log.error("数据错误!跳过本行数据");
					errorMsgSB.append("第" + line + "行:" + str
							+ "   数据错误,导入失败<br>");
					continue;
				}

				String cardSerial = null;
				String cardPwd = null;
				String cardPrice = null;// 面值

				try {
					cardSerial = strArr[0];
					cardPwd = strArr[1];
					cardPrice = strArr[2];// 面值
				} catch (Exception e) {
					log.error("数据错误!跳过本行数据");
					errorMsgSB.append("第" + line + "行:" + str
							+ "   数据错误,导入失败<br>");
					continue;
				}

				String cardEffectTimeStr = null;

				Date cardEffectTime = null;

				try {
					cardEffectTimeStr = strArr[3];
					cardEffectTime = sdf.parse(cardEffectTimeStr);
				} catch (Exception e) {
					// TODO: handle exception
				}

				CardInfo cardInfo = new CardInfo();
				cardInfo.setCardId(UUID.randomUUID().toString());
				cardInfo.setCardSerial(cardSerial);
				cardInfo.setCardPassword(cardPwd);
				cardInfo.setCardPrice(Integer.parseInt(cardPrice));
				cardInfo.setCardImportBatchNum(cardImportBatchNum);
				if (cardEffectTime == null) {
					if ("0".equals(iseffect)) {
						cardInfo.setCardEffectTime(getDayAddHHmmss(twoYearLater));
					}
				} else {
					cardInfo.setCardEffectTime(getDayAddHHmmss(cardEffectTime));
				}
				if (StringUtils.isNotBlank(operatorsType)) {
					cardInfo.setOperatingAgenciesType(operatorsType);
				}
				if (StringUtils.isNotBlank(phoneType)) {
					cardInfo.setPhoneType(phoneType);
				}
				if (StringUtils.isNotBlank(useLevel)) {
					try {
						cardInfo.setUseLevel(Integer.valueOf(useLevel));
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				cardInfo.setAdaptableArea(null);
				cardInfo.setEnable(true);
				cardInfo.setCardName(cardName);
				if (StringUtils.isNotBlank(province)) {
					cardInfo.setAdaptableArea(province);
				}
				if (StringUtils.isNotBlank(areaCity)) {
					cardInfo.setAdaptableArea(areaCity);
				}
				cardInfo.setStockSupplierId(supplier);
				cardInfo.setUpdateOperator(getCurrentOperator().getUserId());
				cardInfo.setStatus(1);// 在库

				// batchList.add(cardInfo);
				// if (batchList.size() > 0 && batchList.size() % size == 0) {
				// boolean bool = cardInfoService.insertCardInfoBatch(
				// batchList, userInfoVO);
				// if (!bool) {
				// errorMsgSB.append("第" + line + "行:" + str
				// + "   数据错误,导入失败<br>");
				// count = count + batchList.size();
				// }
				// }
				boolean bool = false;
				try {
					bool = cardInfoService.saveCardInfo(cardInfo,
							getCurrentOperator());
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!bool) {
					errorMsgSB.append("第" + line + "行:" + str
							+ "   数据错误,导入失败<br>");
					continue;
				}

				// System.out.println("cardNo:" + cardSerial + ",cardPwd:"
				// + cardPwd + ",cardParVale:" + cardPrice + ",cardTime:"
				// + cardEffectTimeStr);

				if (totalPrice == 0) {
					totalPrice = Integer.parseInt(cardPrice);
				}
				count++;
			}

			CardImportLog importLog = new CardImportLog();
			importLog.setId(UUID.randomUUID().toString());
			importLog.setCardBatchNum(cardImportBatchNum);
			importLog.setImportCardName(cardName);
			importLog.setImportCardMoney(totalPrice * count);
			importLog.setImportCardNumber(count);
			importLog.setImportCardPrice(totalPrice);

			if (getCurrentOperator() != null) {
				importLog.setOperator(getCurrentOperator().getUserId());
			}
			importLog.setCardImportDate(new Date());
			importLog.setRemark("");

			cardImportLogService.insert(importLog, getCurrentOperator());

		} else if (StringUtils.isNotBlank(uploadFileName)
				&& uploadFileName.toLowerCase().endsWith(".xsl")) {

		}
		errorMsg = errorMsgSB.toString();
		// 关闭输入流
		bis.close();
		// 关闭输出流
		// os.close();

		log.info("使用时间:" + (System.currentTimeMillis() - useTime) + "毫秒");
		redirectionUrl = "card_management!list.htm";
		return SUCCESS;
	}

	/**
	 * 获取天(23:59:59)
	 * 
	 * @param d
	 * @return
	 */
	private Date getDayAddHHmmss(Date d) {
		if (d != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(d);
			cal.set(Calendar.HOUR, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			cal.set(Calendar.MILLISECOND, 999);
			d = cal.getTime();
		}
		return d;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getCardName() {
		return cardName;
	}

	public void setCardName(String cardName) {
		this.cardName = cardName;
	}

	public String getOperatorsType() {
		return operatorsType;
	}

	public void setOperatorsType(String operatorsType) {
		this.operatorsType = operatorsType;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getIseffect() {
		return iseffect;
	}

	public void setIseffect(String iseffect) {
		this.iseffect = iseffect;
	}

	public String getSupplier() {
		return supplier;
	}

	public void setSupplier(String supplier) {
		this.supplier = supplier;
	}

	public String getSupplyDate() {
		return supplyDate;
	}

	public void setSupplyDate(String supplyDate) {
		this.supplyDate = supplyDate;
	}

	public String getUseLevel() {
		return useLevel;
	}

	public void setUseLevel(String useLevel) {
		this.useLevel = useLevel;
	}

	public SystemProductQuery getSystemProductQuery() {
		return systemProductQuery;
	}

	public void setSystemProductQuery(SystemProductQuery systemProductQuery) {
		this.systemProductQuery = systemProductQuery;
	}

	public List<StockSupplier> getStockSuppliersList() {
		return stockSuppliersList;
	}

	public void setStockSuppliersList(List<StockSupplier> stockSuppliersList) {
		this.stockSuppliersList = stockSuppliersList;
	}

	public String getSystemProductId() {
		return systemProductId;
	}

	public void setSystemProductId(String systemProductId) {
		this.systemProductId = systemProductId;
	}

	public String getAreaCity() {
		return areaCity;
	}

	public void setAreaCity(String areaCity) {
		this.areaCity = areaCity;
	}

	public List<Operation> getOperationList() {
		return operationList;
	}

	public void setOperationList(List<Operation> operationList) {
		this.operationList = operationList;
	}

	public String getPhoneType() {
		return phoneType;
	}

	public void setPhoneType(String phoneType) {
		this.phoneType = phoneType;
	}

	public List<PhoneType> getPhoneTypeList() {
		return phoneTypeList;
	}

	public void setPhoneTypeList(List<PhoneType> phoneTypeList) {
		this.phoneTypeList = phoneTypeList;
	}

}
